import { env } from 'process'
import crypto from 'crypto'
// import Shop from '../model/shop'

export const getNowTime = () => {
	const nowTime = new Date()
	const year = nowTime.getFullYear()
	const month = nowTime.getMonth() + 1
	const day = nowTime.getDate()
	const hour = nowTime.getHours()
	const minute = nowTime.getMinutes()
	const second = nowTime.getSeconds()
	return `${year}-${month >= 10 ? month : `0${month}`}-${
		day >= 10 ? day : `0${day}`
	} ${hour >= 10 ? hour : `0${hour}`}:${
		minute >= 10 ? minute : `0${minute}`
	}:${second >= 10 ? second : `0${second}`}`
}

export const getParamData = async (config) => {
	config.param = config.param || config.data
    let access_token = config.param.access_token || ''
    if(access_token) {
        delete config.param.access_token
    }
	const method = config.url.replace(/\//, '.')
	const timestamp = getNowTime()

	const paramPattern = `${env.APP_SECRET}app_key${
		env.APP_KEY
	}method${method}param_json${JSON.stringify(
		orderedStringify(config.param)
	)}timestamp${timestamp}v${env.V}${env.APP_SECRET}`
	const has = crypto.createHmac('sha256', env.APP_SECRET)
	const ahte = has.update(paramPattern)
	const paramData = {
		app_key: env.APP_KEY,
		method,
		timestamp,
		v: env.V,
		sign_method: env.SIGN_METHOD,
		param_json: JSON.stringify(config.param),
		sign: ahte.digest('hex'),
	}
    if(access_token) {
        paramData.access_token = access_token
    }
    // if(config.url !== 'token/create' && config.param.shop_id) {
    //     Shop.findOne({
    //         shop_id: config.param.shop_id
    //     })
    // }
	// console.log('paramData', paramData, 'paramData++')
	return paramData
	function orderedStringify(obj) {
		// 序列化并排序
		const sortedObj = {}
		const keys = Object.keys(obj)
		keys.sort((a, b) => a.localeCompare(b)).forEach((key) => {
			if (typeof obj[key] === 'object' && !Array.isArray(obj[key]) && (obj[key] !== null) && (obj[key] !== undefined)) {
				sortedObj[key] = orderedStringify(obj[key])
				return
			}
			if (typeof obj[key] === 'object' && Array.isArray(obj[key])) {
				sortedObj[key] = obj[key].map((rs) => {
					if ((typeof rs === 'object') && (rs !== null) && (rs !== undefined)) {
						return orderedStringify(rs)
					}
					return rs
				})
				return
			}
			if (typeof obj[key] === 'number') {
				obj[key] = obj[key].toFixed(6) * 1
			}
			sortedObj[key] = obj[key]
		})
		return sortedObj
	}
}
